import { defineStore } from "pinia"
import { useUserInfoStore } from "../userInfo"
export const useKeyHandleStore = defineStore("keyHandle", {
	state() {
		return {
			handle: {},
		}
	},
	actions: {
		startKeyHandle() {
			const userInfoStore = useUserInfoStore()
			window.addEventListener("keydown", event => {
				if (!userInfoStore.isLogin) return
				Object.values(this.handle).forEach(handle => {
					if (!handle) return
					if (
						(typeof handle.key === "string" && handle.key !== event.key) ||
						(Array.isArray(handle.key) && !handle.key.includes(event.key))
					) {
						return
					}
					if (handle.ctrl && !event.ctrlKey) return
					if (handle.shift && !event.shiftKey) return
					if (handle.alt && !event.altKey) return
					if (handle.prevent) {
						event.preventDefault()
					}
					handle.handle(event)
				})
			})
		},
		addKeyHandle(name, handle, keys, options) {
			this.handle[name] = {
				key: keys,
				handle,
				ctrl: options?.includes("ctrl"),
				shift: options?.includes("shift"),
				alt: options?.includes("alt"),
				prevent: options?.includes("prevent"),
			}
		},
		removeKeyHandle(name) {
			if (this.handle.hasOwnProperty(name)) {
				delete this.handle[name]
			}
		},
	},
})
